package org.psyduck.security.config;

import cn.hutool.core.util.StrUtil;
import org.psyduck.common.utils.Global;
import org.psyduck.security.model.User;
import org.psyduck.security.service.SecurityUserService;
import org.psyduck.security.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtTokenFilter extends OncePerRequestFilter {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    SecurityUserService userService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader(Global.TOKEN_HEADER);
        if(StrUtil.isBlank(token)){
            token = request.getParameter("token");
        }
        if (StrUtil.isNotBlank(token) && !token.equals("undefined")) {
            String username = jwtUtils.getUsernameFromToken(token);
            if (jwtUtils.containToken(token) && null != username && null == SecurityContextHolder.getContext().getAuthentication()) {
                User user = jwtUtils.getUserFromToken(token);
                user.setAuthorities(userService.getCurrentUserAuthorities(user.getId()));
                if (jwtUtils.validateToken(token, user)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
        }
        chain.doFilter(request, response);
    }

}
